using System;
using System.Collections.Generic;
using System.Xml;

namespace Clandestine.Engines.Field
{
	public delegate void SpritesheetAddHandler(string filename);

	// Contains all spritesheets available
	public class Spritesheets : List<Spritesheet>
	{	
		public Map Map { get; private set; }
		public event SpritesheetAddHandler SpritesheetAdd;
	
		public Spritesheets(Map map)
		{
			this.Map = map;
		}
		
		public int IndexOf(string filename)
		{
			for (int i = 0; i < this.Count; i++)
				if (this[i].Filename == filename)
					return i;
			return -1;
		}
		
		public Dictionary<int, int> Load(XmlReader xml)
		{
			Dictionary<int, int> remapping = new Dictionary<int, int>(); // if an ID we load already exists, this gets a nice remapping!
		
			while(xml.Read())
			{
				if (xml.NodeType == XmlNodeType.Element)
                {
                    switch (xml.Name)
                    {
						case "spritesheet":
							string filename = xml.GetAttribute("filename");
							int id = int.Parse(xml.GetAttribute("id"));
							
							int index = this.LoadSpritesheet(filename);
							remapping.Add(id, index);
							break;
                    }
               	} else if ((xml.NodeType == XmlNodeType.EndElement) && (xml.Name == "spritesheets"))
                	return remapping;
			}
			return remapping;
		}
		
		public void Save(XmlWriter xml, IEnumerable<Spritesheet> spritesheetsUsed)
		{
			List<Spritesheet> saved = new List<Spritesheet>(); // so we dont save the same one twice.
			xml.WriteStartElement("spritesheets");
			
			// Iterate!
			foreach (Spritesheet s in spritesheetsUsed)
				if (!saved.Contains(s))
				{
					xml.WriteStartElement("spritesheet");
					xml.WriteAttributeString("id", s.ID.ToString());
					xml.WriteAttributeString("filename", s.Filename);
					xml.WriteEndElement();
				
					saved.Add(s);	
				}
			
			xml.WriteEndElement();
		}
		
		// returns the index in the List<>
		public int LoadSpritesheet(string filename)
		{
			// If already loaded, just return the index
			int index = this.IndexOf(filename);
			if (index >= 0)
				return index;
			
			// Otherwise, load it!
			index = this.Count;
			this.Add(new Spritesheet(this.Map, filename, this.Map.GridSize));
			
			// Events!
			if (SpritesheetAdd != null)
				SpritesheetAdd(filename);
			
			// We added to the end, so return it's index!
			return index;
		}
	}
}

